/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Notepad;

import java.awt.HeadlessException;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author HP 6200 Pro
 */
public class notepad extends javax.swing.JFrame {

    /**
     * Creates new form notepad
     */
    public notepad() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuItem1 = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtSoanThao = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        mniNew = new javax.swing.JMenuItem();
        mniOpen = new javax.swing.JMenuItem();
        mniSave = new javax.swing.JMenuItem();
        mniSaveAs = new javax.swing.JMenuItem();
        mniPrint = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        mniLietKe = new javax.swing.JMenuItem();

        jMenuItem1.setText("jMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(600, 400));
        getContentPane().setLayout(new javax.swing.OverlayLayout(getContentPane()));

        txtSoanThao.setColumns(20);
        txtSoanThao.setRows(5);
        txtSoanThao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtSoanThaoKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(txtSoanThao);
        txtSoanThao.getAccessibleContext().setAccessibleName("");

        getContentPane().add(jScrollPane1);

        jMenu1.setText("File");

        mniNew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        mniNew.setText("New");
        mniNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniNewActionPerformed(evt);
            }
        });
        jMenu1.add(mniNew);

        mniOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        mniOpen.setText("Open");
        mniOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniOpenActionPerformed(evt);
            }
        });
        jMenu1.add(mniOpen);

        mniSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        mniSave.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        mniSave.setText("Save");
        mniSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniSaveActionPerformed(evt);
            }
        });
        jMenu1.add(mniSave);

        mniSaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mniSaveAs.setText("Save As");
        mniSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniSaveAsActionPerformed(evt);
            }
        });
        jMenu1.add(mniSaveAs);

        mniPrint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        mniPrint.setText("Print");
        mniPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniPrintActionPerformed(evt);
            }
        });
        jMenu1.add(mniPrint);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");

        mniLietKe.setText("Liệt kê");
        mniLietKe.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniLietKeActionPerformed(evt);
            }
        });
        jMenu2.add(mniLietKe);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mniSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniSaveActionPerformed
        // TODO add your handling code here:
        if (daLuuDuLieu == true) {
            ghiDuLieu(viTriFile);
        } else {
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showSaveDialog(notepad.this) == JFileChooser.APPROVE_OPTION) {

                File file = fileChooser.getSelectedFile();
                // save to file
                viTriFile = file.getAbsolutePath();
                ghiDuLieu(viTriFile);
                daLuuDuLieu = true;
            }
        }
    }//GEN-LAST:event_mniSaveActionPerformed

    private void mniNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniNewActionPerformed
        int length = txtSoanThao.getText().length();

        // Nếu đang có nội dung mới, gọi thông báo đề xuất lưu file
        if (length != 0 && noiDungDaThayDoi == true) {
            FileChuaLuu();
        } else {
            txtSoanThao.setText(null);
        }
    }//GEN-LAST:event_mniNewActionPerformed


    private void mniOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniOpenActionPerformed
        // TODO add your handling code here:
        // Nếu đang có nội dung mới, gọi thông báo đề xuất lưu file

        if (noiDungDaThayDoi == true) {
            FileChuaLuu();
        } else {
            //Create a file chooser
            final JFileChooser fc = new JFileChooser();

            //In response to a button click:
            int returnVal = fc.showOpenDialog(notepad.this);

            // APPROVE_OPTION: Xác nhận mở file
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                // Nạp file
                File file = fc.getSelectedFile();
                viTriFile = file.getAbsolutePath();
                // Đọc nội dung từ vị trí của file
                String noiDung = docDuLieu(viTriFile);

                //DocFile df = new DocFile(file.getAbsolutePath());
                //df.start();
                //String noiDung = df.getNoiDung();
                // Xóa trắng vùng soạn thảo để nạp nội dung mới.
                txtSoanThao.setText(noiDung);

                // Đổi tiêu đề của cửa sổ
                Notepad.notepad.this.setTitle(file.getName());

                daLuuDuLieu = true;
            }
        }
    }//GEN-LAST:event_mniOpenActionPerformed

    private void txtSoanThaoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSoanThaoKeyTyped
        // TODO add your handling code here:
        noiDungDaThayDoi = true;
    }//GEN-LAST:event_txtSoanThaoKeyTyped

    private void mniSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniSaveAsActionPerformed
        // TODO add your handling code here:
        daLuuDuLieu = false;
        mniSaveActionPerformed(evt);
    }//GEN-LAST:event_mniSaveAsActionPerformed

    private void mniPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniPrintActionPerformed
        try {
            // TODO add your handling code here:
            PrinterJob pj = PrinterJob.getPrinterJob();
            if (pj.printDialog()) {
                pj.print();
            }
        } catch (PrinterException ex) {
            Logger.getLogger(notepad.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_mniPrintActionPerformed

    private void mniLietKeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniLietKeActionPerformed
        // TODO add your handling code here:
        final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setAcceptAllFileFilterUsed(false);
        int returnVal = fc.showOpenDialog(notepad.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            // Nạp file
            File file = fc.getSelectedFile();

            // Đọc nội dung từ vị trí của file
            String[] children = file.list();
            if (children == null) {
                System.out.println("does not exist or is not a directory");
            } else {
                for (int i = 0; i < children.length; i++) {
                    String filename = children[i] + "\n";
                    txtSoanThao.append(filename);

                }
            }

            //df.start();
            //String noiDung = df.getNoiDung();
            // Xóa trắng vùng soạn thảo để nạp nội dung mới.
            // Đổi tiêu đề của cửa sổ
            Notepad.notepad.this.setTitle(file.getName());

            daLuuDuLieu = true;
        }

    }//GEN-LAST:event_mniLietKeActionPerformed

    private void ghiDuLieu(String absolutePath) {
        try {
            FileOutputStream fos = new FileOutputStream(absolutePath);
            PrintWriter pw = new PrintWriter(fos);

            for (String line : txtSoanThao.getText().split("\\n")) {
                pw.println(line);
            }
            pw.close();
            fos.flush();
            fos.close();

            noiDungDaThayDoi = false;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(notepad.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(notepad.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Đọc nội dung file text
     *
     * @param duongDan
     */
    private String docDuLieu(String duongDan) {
        try {
            String noiDung = "";
            try (FileReader file = new FileReader(duongDan)) {
                BufferedReader dataFile = new BufferedReader(file);

                String dongHienTai = null;
                while ((dongHienTai = dataFile.readLine()) != null) {
                    // Nối thêm ký tự ngắt từng dòng
                    noiDung += dongHienTai + "\n";
                }
                return noiDung;
            }
        } catch (IOException e) {
            // Khi ko doc duoc file muon xuat j ra thi e viet vào day
            e.printStackTrace();
        }
        return null;
    }

    private void FileChuaLuu() throws HeadlessException {
        //ChuaLuu frmChuaLuu = new ChuaLuu();
        //JOptionPane.showOptionDialog(null, frmChuaLuu, "Chưa lưu", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{}, null);

        int luaChon = JOptionPane.showConfirmDialog(this, "Lưu file?", "Save", JOptionPane.YES_NO_CANCEL_OPTION);

        switch (luaChon) {
            // Đồng ý lưu
            case JOptionPane.YES_OPTION: {
                mniSaveActionPerformed(null);
            }
            break;
            // Không đồng ý lưu
            case JOptionPane.NO_OPTION: {
                noiDungDaThayDoi = false;
                mniOpenActionPerformed(null);
            }
            break;
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(notepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(notepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(notepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(notepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new notepad().setVisible(true);
            }
        });
    }
    String viTriFile = null;
    boolean daLuuDuLieu = false;
    boolean noiDungDaThayDoi = false;

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuItem mniLietKe;
    private javax.swing.JMenuItem mniNew;
    private javax.swing.JMenuItem mniOpen;
    private javax.swing.JMenuItem mniPrint;
    private javax.swing.JMenuItem mniSave;
    private javax.swing.JMenuItem mniSaveAs;
    private javax.swing.JTextArea txtSoanThao;
    // End of variables declaration//GEN-END:variables
}
